package com.qixiaobao.statistic.service.impl;

import com.qixiaobao.common.core.domain.entity.SysUser;
import com.qixiaobao.common.utils.IdcardUtils;
import com.qixiaobao.common.utils.StringUtils;
import com.qixiaobao.statistic.domain.dto.PersonStatisticDTO;
import com.qixiaobao.statistic.domain.vo.PersonDayStatisticVO;
import com.qixiaobao.statistic.domain.vo.PersonStatisticVO;
import com.qixiaobao.statistic.mapper.InsurePersonStatisticMapper;
import com.qixiaobao.statistic.service.IInsurePersonStatisticService;
import com.qixiaobao.system.domain.Dict;
import com.qixiaobao.system.domain.SlaveUser;
import com.qixiaobao.system.mapper.ActualCompanyMapper;
import com.qixiaobao.system.mapper.DictMapper;
import com.qixiaobao.system.mapper.SlaveUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Description 投保人员统计  业务层处理
 * @Author yangxm
 * @Date 2025/7/8 15:22
 */
@Slf4j
@Service
public class InsurePersonStatisticServiceImpl implements IInsurePersonStatisticService {

    @Autowired
    private InsurePersonStatisticMapper insurancePersonStatisticMapper;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private SlaveUserMapper slaveUserMapper;
    @Autowired
    private ActualCompanyMapper actualCompanyMapper;

    /**
     * 投保人员统计
     * @param personStatisticDTO
     * @return
     */
    @Override
    public List<PersonStatisticVO> statistic(PersonStatisticDTO personStatisticDTO) {
        long begin = System.currentTimeMillis();
        List<PersonStatisticVO> list = insurancePersonStatisticMapper.selectInsurePersonStatisticList(personStatisticDTO);
        log.info("查询投保人员统计列表，sql耗时：{}", System.currentTimeMillis() - begin);
        //数据封装
        putInsurePersonStatistic(list);
        log.info("查询投保人员统计列表，总耗时：{}", System.currentTimeMillis() - begin);
        return list;
    }

    /**
     * @Description 投保人员汇总 列表
     * @Author yangxm
     * @Date 2025/7/9 10:00
     * @param personStatisticDTO
     * @return java.util.List<com.qixiaobao.statistic.domain.vo.PersonStatisticVO>
     */
    @Override
    public List<PersonStatisticVO> summary(PersonStatisticDTO personStatisticDTO) {
        long begin = System.currentTimeMillis();
        List<PersonStatisticVO> list = insurancePersonStatisticMapper.selectInsurePersonSummaryList(personStatisticDTO);
        log.info("查询投保人员汇总列表，sql耗时：{}", System.currentTimeMillis() - begin);
        //数据封装
        putInsurePersonStatistic(list);
        log.info("查询投保人员汇总列表，总耗时：{}", System.currentTimeMillis() - begin);
        return list;
    }

    /**
     * @Description 查询 天保人员统计 列表
     * @Author yangxm
     * @Date 2025/7/9 10:48
     * @param personStatisticDTO
     * @return java.util.List<com.qixiaobao.statistic.domain.vo.PersonDayStatisticVO>
     */
    @Override
    public List<PersonDayStatisticVO> selectStatisticListForDay(PersonStatisticDTO personStatisticDTO) {
        long begin = System.currentTimeMillis();
        List<PersonDayStatisticVO> list = insurancePersonStatisticMapper.selectStatisticListForDay(personStatisticDTO);
        log.info("查询日单投保人员统计列表，sql耗时：{}", System.currentTimeMillis() - begin);
        //数据封装
        putInsurePersonDayStatistic(list);
        log.info("查询日单投保人员统计列表，总耗时：{}", System.currentTimeMillis() - begin);
        return list;
    }

    /**
     * @Description 查询 天保人员汇总 列表
     * @Author yangxm
     * @Date 2025/7/9 14:12
     * @param personStatisticDTO
     * @return java.util.List<com.qixiaobao.statistic.domain.vo.PersonDayStatisticVO>
     */
    @Override
    public List<PersonDayStatisticVO> selectSummaryListForDay(PersonStatisticDTO personStatisticDTO) {
        long begin = System.currentTimeMillis();
        List<PersonDayStatisticVO> list = insurancePersonStatisticMapper.selectSummaryListForDay(personStatisticDTO);
        log.info("查询日单投保人员汇总列表，sql耗时：{}", System.currentTimeMillis() - begin);
        //数据封装
        putInsurePersonDayStatistic(list);
        log.info("查询日单投保人员汇总列表，总耗时：{}", System.currentTimeMillis() - begin);
        return list;
    }

    /**
     * 数据封装
     * @param list
     */
    private void putInsurePersonDayStatistic(List<PersonDayStatisticVO> list) {
        if (StringUtils.isNotEmpty(list)){
            //获取特定字典
            String[] typeArray=new String[]{"mealname","insureperiod","maimRatio","jobtype","insuretype","extension", "dept"};
            List<Dict> dictList = dictMapper.selectDictListByTypeArray(typeArray);
            Map<String, Map<String, String>> dictMap = new ConcurrentHashMap<>();
            if (Optional.ofNullable(dictList).isPresent()) {
                dictMap = dictList.stream().collect(Collectors.groupingBy(Dict::getType, Collectors.toMap(Dict::getK, Dict::getVal)));
            }
            Map<String, String> mealNameMap = dictMap.get("mealname");
            Map<String, String> maimRatioMap = dictMap.get("maimRatio");
            Map<String, String> insureperiodMap = dictMap.get("insureperiod");
            Map<String, String> insuretypeMap = dictMap.get("insuretype");
            Map<String, String> jobtypeMap = dictMap.get("jobtype");
            Map<String, String> extensionMap = dictMap.get("extension");
            Map<String, String> deptMap = dictMap.get("dept");
            //所有的用户信息
            Map<Long, String> userNickNameMap = slaveUserMapper.selectUsernameList().stream().collect(Collectors.toMap(SlaveUser::getId, SlaveUser::getUsername));
            //循环体
            PersonDayStatisticVO item;
            int sex;
            for (int i = 0; i < list.size(); i++) {
                item = list.get(i);
                //序号
                item.setIndex(i + 1);
                //性别
                if (StringUtils.isNotBlank(item.getIdType()) && "身份证".equals(item.getIdType())){
                    try{
                        //性别(M-男，F-女，N-未知)
                        sex = IdcardUtils.getGenderByIdCard2(item.getPid());
                        if (sex == 1){
                            item.setSex("男");
                        }else if (sex == 0){
                            item.setSex("女");
                        }else {
                            item.setSex("未知");
                        }
                    } catch (Exception e) {
                        log.error("{},获取性别异常：",item.getPid(), e);
                        item.setSex("");
                    }
                }
                //字典转换
                item.setBelongCompanyName(deptMap.get(item.getBelongCompanyId()));
                item.setMealNameVal(mealNameMap.get(item.getMealName()));
                item.setJobTypeVal(jobtypeMap.get(item.getJobType()));
                item.setMaimRatioVal(maimRatioMap.get(item.getMaimRatio()));
                item.setInsurePeriodVal(insureperiodMap.get(item.getInsurePeriod()));
                item.setExtensionVal(extensionMap.get(item.getExtension()));
                item.setInsureTypeVal(insuretypeMap.get(item.getInsureType()));
                //客服
                item.setServiceName(userNickNameMap.getOrDefault(item.getServiceId(), ""));
                //是否新实际用工单位标记
                //item.setNewActualCompanyFlag(item.getActualCompanyId() == null ? "是" : "否");
                item.setFinanceReckonVal("0".equals(item.getFinanceReckon()) ? "否" : "是");
            }
        }
    }

    /**
     * 数据封装
     * @param list
     */
    private void putInsurePersonStatistic(List<PersonStatisticVO> list) {
        if (StringUtils.isNotEmpty(list)){
            //获取特定字典
            String[] typeArray=new String[]{"mealname","insureperiod","maimRatio","jobtype","insuretype","extension", "dept"};
            List<Dict> dictList = dictMapper.selectDictListByTypeArray(typeArray);
            Map<String, Map<String, String>> dictMap = new ConcurrentHashMap<>();
            if (Optional.ofNullable(dictList).isPresent()) {
                dictMap = dictList.stream().collect(Collectors.groupingBy(Dict::getType, Collectors.toMap(Dict::getK, Dict::getVal)));
            }
            Map<String, String> mealNameMap = dictMap.get("mealname");
            Map<String, String> maimRatioMap = dictMap.get("maimRatio");
            Map<String, String> insureperiodMap = dictMap.get("insureperiod");
            Map<String, String> insuretypeMap = dictMap.get("insuretype");
            Map<String, String> jobtypeMap = dictMap.get("jobtype");
            Map<String, String> extensionMap = dictMap.get("extension");
            Map<String, String> deptMap = dictMap.get("dept");
            //所有的用户信息
            Map<Long, String> userNickNameMap = slaveUserMapper.selectUsernameList().stream().collect(Collectors.toMap(SlaveUser::getId, SlaveUser::getUsername));
            //循环体
            PersonStatisticVO item;
            int sex;
            for (int i = 0; i < list.size(); i++) {
                item = list.get(i);
                //序号
                item.setIndex(i + 1);
                //性别
                if (StringUtils.isNotBlank(item.getIdType()) && "身份证".equals(item.getIdType())){
                    try{
                        //性别(M-男，F-女，N-未知)
                        sex = IdcardUtils.getGenderByIdCard2(item.getPid());
                        if (sex == 1){
                            item.setSex("男");
                        }else if (sex == 0){
                            item.setSex("女");
                        }else {
                            item.setSex("未知");
                        }
                    } catch (Exception e) {
                        log.error("{},获取性别异常：",item.getPid(), e);
                        item.setSex("");
                    }
                }
                //字典转换
                item.setBelongCompanyName(deptMap.get(item.getBelongCompanyId()));
                item.setMealNameVal(mealNameMap.get(item.getMealName()));
                item.setJobTypeVal(jobtypeMap.get(item.getJobType()));
                item.setMaimRatioVal(maimRatioMap.get(item.getMaimRatio()));
                item.setInsurePeriodVal(insureperiodMap.get(item.getInsurePeriod()));
                item.setExtensionVal(extensionMap.get(item.getExtension()));
                item.setInsureTypeVal(insuretypeMap.get(item.getInsureType()));
                //客服
                item.setServiceName(userNickNameMap.getOrDefault(item.getServiceId(), ""));
                //是否新实际用工单位标记
                item.setNewActualCompanyFlag(item.getActualCompanyId() == null ? "是" : "否");
                item.setFinanceReckonVal("0".equals(item.getFinanceReckon()) ? "否" : "是");
            }
        }
    }
}
